package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @date 2024/6/5 16:58
 */
@Component
@RequiredArgsConstructor
public class LoginAuthGlobalFilter implements GlobalFilter, Ordered {
    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、获取当前请求url
        ServerHttpRequest request = exchange.getRequest();
        String currentUrl = request.getPath().toString();

        // 2、判断当前url是否需要拦截鉴权
        boolean isAllow = isAllowPath(currentUrl);
        
        // 3、如果不需要鉴权，直接放行
        if(isAllow){
            return chain.filter(exchange);
        }
        
        // 4、如果需要，获取token
        String token = request.getHeaders().getFirst("Authorization");

        // 5、解析token
        Long userId;
        try {
             userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        // 6、将解析出的userid存入请求头
        ServerWebExchange newExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userId.toString()))
                .build();

        // 7、放行
        return chain.filter(newExchange);
    }

    /**
     * 判断当前请求url是否允许放行
     * @param currentUrl
     * @return
     */
    private boolean isAllowPath(String currentUrl) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,currentUrl)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
